#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author   : long.hai
@Contact  : 1982964634@qq.com
"""
import json
import traceback
from _base.base import BasePage
from _step.base import BaseStep
from _step.step import StepList, Step, TestCaseList
from control.load_variable import LoadVariable


async def single_debug(base_page: BasePage, variables, testcase: dict):
    """
    单个测试用例调试或单个步骤调试
    :param base_page: 页面对象
    :param variables: 全局/环境/用例变量
    :param testcase: 测试数据
    """
    # 加载基础数据
    info = testcase["info"]
    step_data = testcase["steps"]
    # 初始化对象
    lv = LoadVariable(base_page)
    base_step = BaseStep(base_page)
    try:
        # 加载全局/环境/用例变量
        await lv.global_and_env(variables)
        await lv.case(variables["case"])

        if isinstance(step_data, dict):
            step = Step(step_data)
            await base_step.single_step(step)
        else:
            steps = StepList(step_data)
            await base_step.multiple_step(steps)
            if info["config"]:
                for var in info["config"].split(','):
                    if var in base_page.case_pool:
                        base_page.env_pool[var] = base_page.case_pool[var]
    except Exception as e:
        traceback.print_exc()
        await base_page.log_error(f"用例调试异常: {str(e)}")
    finally:
        await base_step.send_variables()  # 执行结束发送用例变量池数据
        await base_step.custom('{"code": 201}')  # 发送执行完成信息
        await base_page.log_info("用例调试完成。")


async def batch_debug(base_page: BasePage, variables, testcase_list):
    """
    批量调试测试用例
    :param base_page: 页面对象
    :param variables: 全局/环境/用例变量
    :param testcase_list: 测试数据列表
    """
    lv = LoadVariable(base_page)
    base_step = BaseStep(base_page)
    testcase_list = TestCaseList(testcase_list)
    try:
        # 加载全局/环境/用例变量
        await lv.global_and_env(variables)
        for testcase in testcase_list.children:
            try:
                await base_page.log_info(f"用例《{testcase.name}》开始运行。")
                await lv.case(testcase.variables)
                await base_step.multiple_step(testcase.steps)
            except Exception as e:
                await base_page.log_error(str(e))
            finally:
                await base_step.send_variables()
        # 发送执行完成信息
        await base_step.custom('{"code": 201}')
        await base_page.log_info("用例批量调试完成。")
    except Exception as e:
        traceback.print_exc()
        print('batch_runner:', e)
        await base_page.log_error(f"用例批量调试异常: {str(e)}")
